package com.bwie.service.impl;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.OrderDetailMapper;
import com.bwie.mapper.OrderRecordMapper;
import com.bwie.mapper.ProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.*;
import com.bwie.service.UserFeign;
import com.bwie.utils.JwtsUtils;
import com.bwie.utils.R;
import com.sun.org.apache.regexp.internal.RE;
import org.aspectj.weaver.ast.Or;
import org.checkerframework.common.value.qual.IntVal;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.OrderMapper;
import com.bwie.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author :Beyond🎸🎸
* @date : 2025-10-27 10:37:57
* @description
* ${description}
**/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProdInfoMapper prodInfoMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderRecordMapper orderRecordMapper;

    @Autowired
    private HttpServletResponse response;
    @Override
    public R orderService(Order order) {
        //先构建分页参数
        Page<Order> page = new Page<>(order.getPageNum(), order.getPageSize());
        //构建查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
//        订单状态
        if(order.getOrderStatus()!=null){
            wrapper.eq(Order::getOrderStatus,order.getOrderStatus());
        }
//        订单类型
        if(order.getOrderType()!=null){
            wrapper.eq(Order::getOrderType,order.getOrderType());
        }
//        商品名称
        if(StringUtils.isNotEmpty(order.getKeyWord())){
            wrapper.like(Order::getProdInfo,order.getKeyWord())
                    .or().eq(Order::getOrderId,order.getKeyWord());
        }
//        创建时间
        if(order.getStartTime()!=null && order.getEndTime()!=null){
            wrapper.ge(Order::getCreateTime,order.getStartTime())
                    .le(Order::getCreateTime,order.getEndTime());
        }
            wrapper.eq(Order::getDeleteFlag,0);
            wrapper.orderByDesc(Order::getCreateTime);
//            进行分页查询
        Page<Order> orderPage = orderMapper.selectPage(page, wrapper);
//        feign调用用户服务获取用户信息

          if(orderPage.getRecords()!=null&&orderPage.getSize()>0){
              for (Order record : orderPage.getRecords()) {
                  User feignUserNameToSave = userFeign.getUserNameToSave(record.getUserId());
                  if(feignUserNameToSave !=null){
                      record.setUserName(feignUserNameToSave.getUserName());
                  }
              //查询商品图片信息
                 List<String> string = orderDetailMapper.selectProdImageByOrderId(record.getOrderId().intValue());
                  record.setProdImagesList(string);
              }
          }
        return R.OK(orderPage);
    }

    @Override
    public R selectUpGoods() {

        return R.OK(prodInfoMapper.selectUpGoods());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveOrderOk(List<ProdInfo> infoList) {

        String token = request.getHeader("token");
        Integer userIdByToken = JwtsUtils.getUserIdByToken(token);
//        ①先校验参数,购买的商品是否存在
        if(infoList==null||infoList.size()<=0){
            return R.ERROR(500,"请先添加商品信息，再下单");
        }
       BigDecimal totalPrice = BigDecimal.ZERO;
        StringJoiner joiner = new StringJoiner(",");

//        ②获取分布式锁
        RLock lock = redissonClient.getLock("save-order-lock");
//        无限等待获取锁
        lock.lock();
        try {
//            ③校验库存是否充足
            for (ProdInfo prodInfo : infoList) {
//                查询出剩余库存
                ProdInfo oneNum = prodInfoMapper.selectById(prodInfo.getInfoId());
                if(oneNum==null){
                    return R.ERROR(500,"数据异常");
                }
                if(oneNum.getProdStock().intValue()<prodInfo.getBuyNum()){
                    return R.ERROR(500,"商品："+prodInfo.getProdName()+"库存不足");
                }
//                ④扣减库存
                oneNum.setProdStock(oneNum.getProdStock()-prodInfo.getBuyNum());
                oneNum.setUpdateBy(userIdByToken);
                oneNum.setUpdateDate(new Date());
                prodInfoMapper.updateById(oneNum);
//                计算总金额
                 totalPrice = totalPrice.add(oneNum.getProdPrice().multiply(new BigDecimal(prodInfo.getBuyNum())));
//                拼接商品名字
                joiner.add(oneNum.getProdName());
            }
//            ⑤生成订单数据
            Order order = new Order();
//            下单用户
            order.setUserId(userIdByToken);
//            总金额
            order.setOrderAmount(totalPrice);
//            默认未支付
            order.setOrderStatus(0);
//            未删除
            order.setDeleteFlag(0);
            order.setCreateBy(userIdByToken);
            order.setCreateTime(new Date());
            order.setOrderType(0);
//            商品信息
            order.setProdInfo(joiner.toString());
//            雪花算法生成订单编号
            order.setOrderNo(IdUtil.getSnowflake(1,1).nextIdStr());
            orderMapper.insert(order);
//            ⑥生成订单明细
            for (ProdInfo prodInfo : infoList) {
                OrderDetail orderDetail = new OrderDetail();
//                订单编号
                orderDetail.setOrderId(order.getOrderId().intValue());
//                订单明细id
                orderDetail.setInfoId(prodInfo.getInfoId().intValue());
//                商品id
                orderDetail.setProdId(prodInfo.getProdId().intValue());
//                购买的数量
                orderDetail.setBuyNum(prodInfo.getBuyNum());
//                商品价格
                orderDetail.setBuyPrice(prodInfo.getProdPrice());
//                审计字段
                orderDetail.setCreateBy(userIdByToken);
                orderDetail.setCreateDate(new Date());
                orderDetail.setDeleteFlag(0);
                orderDetailMapper.insert(orderDetail);
            }
//            ⑦生成订单记录表
            OrderRecord orderRecord = new OrderRecord();
            orderRecord.setOrderId(order.getOrderId().intValue());
            orderRecord.setOptRecord("用户创建订单");
            orderRecord.setCreateDate(new Date());
            orderRecord.setCreateBy(userIdByToken);
            orderRecordMapper.insert(orderRecord);
        }
        finally {
//           ⑧释放锁
            lock.unlock();
        }
        return R.OK();
    }

    @Override
    public void exportOrder() {

//    定义导出工具类
        ExcelUtil<Order> excelUtil = new ExcelUtil<>(Order.class);
//        查询导出数据
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Order::getDeleteFlag,0);
        List<Order> orderList = orderMapper.selectList(lambdaQueryWrapper);
//        使用工具类进行导出
        excelUtil.exportExcel(response,orderList,"订单列表");
    }

    @Override
    public R delBatchOrder(List<Integer> orderIds) {

//        删除订单数据
        for (Integer orderId : orderIds) {
            Order order = orderMapper.selectById(orderId);
            order.setDeleteFlag(1);
            order.setDeleteDate(new Date());
            orderMapper.updateById(order);
            //        删除订单详细数据
            LambdaUpdateWrapper<OrderDetail> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,orderId);
            orderDetailMapper.delete(wrapper);
//            删除订单记录表
            LambdaUpdateWrapper<OrderRecord> wrapper1 = new LambdaUpdateWrapper<>();
            wrapper1.eq(OrderRecord::getOrderId,orderId);
            orderRecordMapper.delete(wrapper1);
        }
        return R.OK();
    }
}
